package com.jeesite.modules.exam.socreResult.web;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.score.dao.DcSupExamScoreDao;
import com.jeesite.modules.exam.score.entity.*;
import com.jeesite.modules.exam.score.service.DcSupExamOrgScoreService;
import com.jeesite.modules.exam.score.service.DcSupExamScoreService;
import com.jeesite.modules.exam.socreResult.dao.DcSupExamOrgSelectDao;
import com.jeesite.modules.exam.socreResult.entity.DcSupExamOrgSelect;
import com.jeesite.modules.exam.socreResult.service.DcSupExamRankingService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.RoleUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RequestMapping("${adminPath}/exam/dcSupExamRanking")
@Controller
public class DcSupExamRankingController extends BaseController {

    private final DcSupExamRankingService dcSupExamRankingService;
    private final SysOfficeUnitService sysOfficeUnitService;
    private final DcSupExamOrgSelectDao selectDao;

    /**
     * 单位排名页面
     * @return
     */
    @RequestMapping("unitRankingView")
    public String unitRankingView(DcSupExamOrgScore dcSupExamOrgScore, Model model){
        model.addAttribute("dcSupExamOrgScore",dcSupExamOrgScore);
        return "modules/exam/scoresResult/unitRanking";
    }

    /**
     * 单项指标排名页面
     * @return
     */
    @RequestMapping("danRankingView")
    public String danRankingView(DcSupExamOrgScore dcSupExamOrgScore, Model model){
        boolean dan_watch = RoleUtils.hasUserRole(UserUtils.getUser().getUserCode(), "dan_watch");
        if(!dan_watch){
            dcSupExamOrgScore.setExameOrg( sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
            dcSupExamOrgScore.setExameOrgName( sysOfficeUnitService.getLatestUnitByOffice().getOfficeName());
        }
        List<DcSupExamOrgSelect> selectDaoList = selectDao.findList(new DcSupExamOrgSelect());
        model.addAttribute("selectOrgs",selectDaoList);
        model.addAttribute("dcSupExamOrgScore",dcSupExamOrgScore);
        return "modules/exam/scoresResult/danRanking";
    }


    /**
     * 指标排名页面
     * @return
     */
    @RequestMapping("indexRankingView")
    public String indexRankingView(DcSupExamOrgScore dcSupExamOrgScore, Model model){
        model.addAttribute("dcSupExamOrgScore",dcSupExamOrgScore);
        return "modules/exam/scoresResult/indexRanking";
    }

    /**
     * 单位排名数据
     */
    @ResponseBody
    @PostMapping("unitListData")
    public List<DcSupExamOrgScore> unitListData(DcSupExamOrgScore dcSupExamOrgScore, HttpServletResponse response, HttpServletRequest request){
        dcSupExamOrgScore.setPage(null);
        List<DcSupExamOrgScore> dcSupExamOrgScorePage = dcSupExamRankingService.unitListData(dcSupExamOrgScore);
        return dcSupExamOrgScorePage;
    }

    /**
     * 单项单位排名数据
     */
    @ResponseBody
    @PostMapping("danUnitListData")
    public Page<DcSupExamDxSort> danUnitListData(DcSupExamDxSort dcSupExamDxSort, HttpServletRequest request, HttpServletResponse response){
        dcSupExamDxSort.setPage(new Page<>(request,response));
        boolean dan_watch = RoleUtils.hasUserRole(UserUtils.getUser().getUserCode(), "dan_watch");
        if(!dan_watch){
            dcSupExamDxSort.setExameOrgName(sysOfficeUnitService.getLatestUnitByOffice().getOfficeName());
            dcSupExamDxSort.setExameOrg(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        }
        Page<DcSupExamDxSort> list=dcSupExamRankingService.danUnitListDataPage(dcSupExamDxSort);
        return list;
    }


    /**
     * 单项指标排名数据
     */
    @ResponseBody
    @PostMapping("indexListData")
    public Page<DcSupExamSumQuotaInfo> indexListData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo, HttpServletRequest request, HttpServletResponse response){
        dcSupExamSumQuotaInfo.setPage(new Page<>(request,response));
        Page<DcSupExamSumQuotaInfo> list=dcSupExamRankingService.findDXRanKingListPage(dcSupExamSumQuotaInfo);
        return list;
    }


    /**
     * 单项指标被考核单位分数数据
     */
    @ResponseBody
    @PostMapping("indexListScoreData")
    public List<DcSupExamSumQuotaInfo> indexListScoreData(DcSupExamSumQuotaInfo dcSupExamSumQuotaInfo){
        dcSupExamSumQuotaInfo.setPage(null);
        List<DcSupExamSumQuotaInfo> unitScoreListData = dcSupExamRankingService.findUnitRankingScoreData(dcSupExamSumQuotaInfo);
        return unitScoreListData;
    }


    /**
     * 评分排名导出
     */
    @GetMapping("/exportSortFile")
    public void exportSortFile(String examId, HttpServletResponse response, HttpServletRequest request) throws Exception{
        List<DcSupExamSortExport> list = dcSupExamRankingService.exprotSort(examId);
        list.forEach(x->{
            String code = x.getGroupUnit();
            x.setGroupUnit(DictUtils.getDictLabel("dc_exam_unit_classification", code, ""));
        });
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("groupUnit","单位分类");
        writer.setColumnWidth(0,35);
        writer.addHeaderAlias("exameName","被考核单位");
        writer.setColumnWidth(0,35);
        writer.addHeaderAlias("myScore","总得分");
        writer.setColumnWidth(1,35);
        writer.addHeaderAlias("ranking","排名");
        writer.write(list,true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("指标评分排名"+ DateUtils.formatDate(new Date(),"yyyyMMdd"),"UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }


    /**
     * 导出单项指标排名数据
     */
    @GetMapping("/exportDxFile")
    public void exportDxFile(DcSupExamDxSort  dcSupExamDxSort, HttpServletResponse response,HttpServletRequest request) throws Exception {
        boolean dan_watch = RoleUtils.hasUserRole(UserUtils.getUser().getUserCode(), "dan_watch");
        if(!dan_watch){
            dcSupExamDxSort.setExameOrgName(sysOfficeUnitService.getLatestUnitByOffice().getOfficeName());
            dcSupExamDxSort.setExameOrg(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        }
        List<DcSupExamDxSortExport> list = dcSupExamRankingService.exportDxSort(dcSupExamDxSort);
//        Map<String, List<DcSupExamDxSortExport>> mapData = list.stream().collect(Collectors.groupingBy(DcSupExamDxSortExport::getCustomSort));
//        ArrayList<DcSupExamDxSortExport> dcSUpExamDxExports = ListUtils.newArrayList();
//        Set<String> customSorts = mapData.keySet().stream().sorted((o1, o2) -> Integer.valueOf(o1).compareTo(Integer.valueOf(o2))).collect(Collectors.toCollection(LinkedHashSet::new));
//        for (String customSort : customSorts) {
//            List<DcSupExamDxSortExport> dcSUpExamDxExportByQuotaContent = mapData.get(customSort);
//            if (dcSUpExamDxExportByQuotaContent.size()>1){
//                dcSUpExamDxExportByQuotaContent.stream().skip(1).forEach(x->x.setCustomSort(""));
//            }
//            dcSUpExamDxExports.addAll(dcSUpExamDxExportByQuotaContent);
//        }

        for (DcSupExamDxSortExport dcSUpExamDxExport : list) {
            //处理字典
//            String code = dcSUpExamDxExport.getQuotaType();
//            dcSUpExamDxExport.setQuotaType(DictUtils.getDictLabel("dc_quotaType", code, ""));

            String groupUnit = dcSUpExamDxExport.getGroupUnit();
            dcSUpExamDxExport.setGroupUnit(DictUtils.getDictLabel("dc_exam_unit_classification", groupUnit, ""));
            //处理显示格式
            if (StringUtils.isNotBlank(dcSUpExamDxExport.getPercentage())){
                dcSUpExamDxExport.setPercentage(dcSUpExamDxExport.getPercentage()+"%");
            }else {
                dcSUpExamDxExport.setPercentage("0.00%");
            }

        }
        String dc_exam_unit_classification = DictUtils.getDictLabel("dc_exam_unit_newclassification", dcSupExamDxSort.getGroupUnit(), "");
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("groupUnit","单位分类");
        writer.setColumnWidth(0,35);
        writer.addHeaderAlias("exameOrgName","被考核单位");
        writer.addHeaderAlias("quotaContent","目标内容");
        writer.setColumnWidth(2,40);
        writer.addHeaderAlias("quotaWeight","权重");
        writer.setColumnWidth(1,15);
        writer.addHeaderAlias("percentage","百分制得分");
        writer.setColumnWidth(5,35);
//        writer.addHeaderAlias("customSort","序号");
        writer.addHeaderAlias("quotaScore","得分");


        writer.addHeaderAlias("ranking","排名");
        writer.write(list,true);


        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
        //设置标题
        String fileName= URLEncoder.encode("单项指标排名"+ DateUtils.formatDate(new Date(),"yyyyMMdd"),"UTF-8");
        if(StringUtils.isNotBlank(dc_exam_unit_classification)){
            fileName =URLEncoder.encode("单项指标"+dc_exam_unit_classification+"排名"+ DateUtils.formatDate(new Date(),"yyyyMMdd"),"UTF-8");
        }
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
    }

}
